package _02生产主和消费者案例;

import java.util.ArrayList;

public class Demo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        Cook cook =new Cook(list);
        Baby baby = new Baby(list);

        cook.start();
        baby.start();
    }
}
class Cook extends Thread{
    private ArrayList<String> list;

    public Cook(ArrayList<String> list) {
        this.list = list;

    }

    int count=0;//包子编号

    @Override
    public void run() {

        while (true){
            try {
                synchronized (list){
                    if (list.size() > 0) {
                        //如果有包子就等待
                        list.wait();
                    }else {
                        //如果没有包子就去做，做好了叫吃货去吃
                        count++;
                        list.add("包子"+count);
                        Thread.sleep(2000);
                        System.out.println("厨师做了"+list.get(0));

                        list.notify();
                    }
                }
            }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

    }
}
class Baby extends Thread{
    private ArrayList<String> list ;

    public Baby(ArrayList<String> list) {
        this.list = list;
    }


    @Override
    public void run() {
        while (true){
            try {
                synchronized (list){
                    if (list.size() > 0) {
                        //如果有包子就吃包子，吃完了叫cook做
                        String bao = list.remove(0);
                        Thread.sleep(1000);
                        System.out.println("吃货吃了"+bao);
                        list.notify();
                    }else {
                        //如果没有包子就去做，做好了叫吃货去吃
                       list.wait();
                    }
                }
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }
}
